<?php

class AuthController extends Zend_Controller_Action{
    
    private $_params;
	private $_auth;
	private $_acl;
    public function init(){
        $this->_params      = $this->_request->getParams();                
        $this->_acl         = new My_Acl();
        $this->view->acl    = $this->_acl;
        $auth=Zend_Auth::getInstance();        
        if($auth->hasIdentity() && $this->_request->getActionName() != 'logout')
            $this->_helper->redirector('index','index', 'default');                                                      
        //$this->_auth        = $this->_acl->checkAllowed();        
        //$this->view->auth   = $this->_auth;
//        $config = new Zend_Config_Ini(CONFIG_PATH . '/application.ini', APPLICATION_ENV);               
        //$layout = Zend_Layout::getMvcInstance();
        //$layout->disableLayout();        
    }
    public function indexAction($error=null){                                           
        $login_form=new Default_Form_Login();
        $this->view->loginForm = $login_form;
        $regis_form=new Default_Form_Regis();
        $this->view->regisForm = $regis_form;        
    }
    public function loginAction (){                                                                     
        if ($this->_request->isPost()){                        
            $loginForm_data = $this->_request->getPost();            
            $login_form=new Default_Form_Login();
            if($login_form->isValid($loginForm_data)){                   
                $adapter = new Zend_Auth_Adapter_DbTable(NULL,'user','email','password','MD5(?)');                                     
                $email = $this->_request->getParam('email');
                $paswd = $this->_request->getParam('password');                        
                $adapter->setIdentity($email);
                $adapter->setCredential($paswd);
                $auth = Zend_Auth::getInstance();
                $auth->setStorage(new Zend_Auth_Storage_Session(SESSION_NAMESPACE));                   
                $result = $auth->authenticate($adapter);                                            
                if ($result->isValid()){
                    $modelUser = new Default_Model_User();                                                           
                    $userCheck = $modelUser->getDataByEmail($email);                                                                                                                                                              
                    if($userCheck->status == 1){                        
                        $auth->getStorage()->write(array('email'=>$userCheck['email'],'userId'=>$userCheck['userId'],'fullName'=>$userCheck['fullName']));                                                                                                                                                                                             
                        $this->_helper->redirector('index','index','default');
                    }else{                        
                        $auth->clearIdentity();
                        $this->view->flag='error';                                        
                        $this->view->mess='Tài khoản của bạn tạm khoá. Vui lòng kiểm tra Email để kích hoạt tài khoản!';
                        $this->view->loginForm_data = $loginForm_data;
                        $this->_forward('index','auth','default');       
                    }                                                                                                                        
                }else{                                        
                    $this->view->flag = 'error';
                    $this->view->mess = 'Username hoặc mật khẩu không đúng!';                    
                    $this->view->loginForm_data = $loginForm_data;
                    $this->_forward('index','auth','default');                                               
                }
            }                                                            
        }else{
            $this->_helper->redirector('index','auth','default');
        }      
    }
    public function regisAction(){
        if($this->_request->isPost()){
            $form_data = $this->_request->getPost();
            $regis_form=new Default_Form_Regis();
            $captcha=$form_data['captcha'];
            $captchaSession = new Zend_Session_Namespace('Zend_Form_Captcha_'.$captcha['id']);
            if($captchaSession->word == $captcha['input']){
                if($regis_form->isValid($form_data)){                                                                                                
                    $addData['fullName'] = $form_data['fullName'];
                    $addData['email'] = $form_data['email'];
                    $addData['password'] = md5($form_data['password']);                
                    
                    $modelUser=new Default_Model_User();                
                    $emailCheck=$modelUser->getDataByEmail($addData['email']);                
                    if(!$emailCheck){                                        
                        $userId=$modelUser->addData($addData);                                            
                        if($userId){
                            $email=$addData['email'];
                            $str=$userId.$email;                                       
                            $random=md5($str);                                               
                            $modelUser->updateData(array('random'=>$random),$userId);                                                                                                
                            $url=BASE_URL.'default/auth/confirm/hash/'.$random;
                                                                                                                      
                            $this->activeAction($email,$url);                                         
                            $this->view->flag='success';                                        
                            $this->view->mess='Đăng ký thành công! Vui lòng kiểm tra Email để kích hoạt tài khoản';
                            $this->_forward('index','auth','default');                        
                        }else{
                            $this->view->flag='error';
                            $this->view->mess = "Đã có lỗi xảy ra. Vui lòng thử lại!";
                            $this->view->regisForm_data=$form_data;
                            $this->_forward('index','auth','default');
                        }
                    }else{
                        $this->view->flag='alert';                                        
                        $this->view->mess='Email '.$email['email'].' đã đăng ký tại hệ thống!';
                        $this->view->regisForm_data=$form_data;
                        $this->_forward('index','auth','default');
                    }                                                                                                                           
                }else{                
                    $this->view->flag='error';                                        
                    $this->view->mess='Bạn chưa điền đầy đủ thông tin!';
                    $this->view->regisForm_data=$form_data;
                    $this->_forward('index','auth','default');                
                }
            }else{
                $this->view->flag='alert';                                        
                $this->view->mess='Mã xác nhận không chính xác! Vui lòng nhập lại !!!';
                $this->view->regisForm_data=$form_data;
                $this->_forward('index','auth','default');
            }                                    
        }else{
            $this->_helper->redirector('index','auth','default');
        }                    
    }    
    public function logoutAction(){                                                
        $auth=Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_helper->redirector('index','auth', 'default');                      
    }    
    public function confirmAction(){        
        $hash=$this->_request->getParam('hash');                
        $modelUser=new Default_Model_User();    
        $user=$modelUser->getDataConfirm($hash);                
        if($user){
            $modelUser->updateStatus($user['userId']);
            $this->view->flag='success';                                        
            $this->view->mess='Kích hoạt tài khoản thành công! Hãy đăng nhập để tiếp tục mua hàng nhé !';
            $this->_forward('index','auth','default');    
        }else{
            $this->view->flag='alert';                                        
            $this->view->mess='Kích hoạt tài khoản không thành công!';
            $this->_forward('index','auth','default');
        }
                                               
    }
    public function activeAction($email,$url){
        $your_name = 'Customer Service';
        $your_email = 'khoale.edu@gmail.com'; //Or your_email@gmail.com for Gmail
        $your_password = '741963456';
        $send_to_name = '';
        $send_to_email = $email;
        
        //SMTP server configuration
        $smtpHost = 'smtp.gmail.com';
        $smtpConf = array(
            'auth' => 'login',
            'ssl' => 'ssl',
            'port' => '465',
            'username' => $your_email,
            'password' => $your_password
        );
        $transport = new Zend_Mail_Transport_Smtp($smtpHost, $smtpConf);

        //Create email
        $mail = new Zend_Mail('UTF-8');                                 
        $mail->setFrom($your_email, $your_name);
        $mail->addTo($send_to_email, $send_to_name);
        $mail->setSubject('Xác nhận đăng ký thành công');
        $mail->setBodyHtml('<table><tr>Link kích hoạt tài khoản: </tr><tr>'.$url.'</tr></table>');
        //$mail->setBodyText('Link kích hoạt tài khoản: '.$url);
                          
        //Send
        $sent = true;
        try {            
            $mail->send($transport);
        }
        catch (Exception $e) {
        $sent = false;
        }                        
    }              
}



